import dotenv from 'dotenv';
import { logger } from '../utils/logger';

// 加载环境变量
dotenv.config();

/**
 * 环境变量配置接口
 */
interface EnvConfig {
  PORT: number;
  NODE_ENV: string;
  MONGODB_URI: string;
  JWT_SECRET: string;
  JWT_EXPIRES_IN: string;
  UPLOAD_PATH: string;
  MAX_FILE_SIZE: number;
  LOG_LEVEL: string;
  SMTP_HOST?: string;
  SMTP_PORT?: number;
  SMTP_USER?: string;
  SMTP_PASS?: string;
}

/**
 * 验证必需的环境变量
 */
const validateEnv = (): EnvConfig => {
  const requiredVars = [
    'PORT',
    'NODE_ENV',
    'MONGODB_URI',
    'JWT_SECRET',
    'JWT_EXPIRES_IN',
    'UPLOAD_PATH',
    'MAX_FILE_SIZE',
    'LOG_LEVEL'
  ];

  const missing = requiredVars.filter(key => !process.env[key]);
  
  if (missing.length > 0) {
    logger.error(`缺少必需的环境变量: ${missing.join(', ')}`);
    process.exit(1);
  }

  return {
    PORT: parseInt(process.env.PORT || '3008', 10),
    NODE_ENV: process.env.NODE_ENV || 'development',
    MONGODB_URI: process.env.MONGODB_URI!,
    JWT_SECRET: process.env.JWT_SECRET!,
    JWT_EXPIRES_IN: process.env.JWT_EXPIRES_IN!,
    UPLOAD_PATH: process.env.UPLOAD_PATH!,
    MAX_FILE_SIZE: parseInt(process.env.MAX_FILE_SIZE || '10485760', 10),
    LOG_LEVEL: process.env.LOG_LEVEL!,
    SMTP_HOST: process.env.SMTP_HOST,
    SMTP_PORT: process.env.SMTP_PORT ? parseInt(process.env.SMTP_PORT, 10) : undefined,
    SMTP_USER: process.env.SMTP_USER,
    SMTP_PASS: process.env.SMTP_PASS,
  };
};

export const config = validateEnv();

export default config;